package de.jonasjelten.jcalc.parser;

import de.jonasjelten.jcalc.exception.JBracketException;
import de.jonasjelten.jcalc.exception.JExpressionParserException;
import de.jonasjelten.jcalc.exception.JParserException;
import de.jonasjelten.jcalc.mathExps.JMathExp;
import de.jonasjelten.jcalc.mathExps.JMathExpList;
import de.jonasjelten.jcalc.mathExps.JSum;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;

/**
 * Sigma-Funktion
 * @author Jonas Jelten
 */
public class JSummationParser extends JExpressionParser {
    // sigma(von,bis,var,rechnung mit $varname$)
    @Override
    public JMathExp parseExpression(String[] args) throws JParserException {
        String varsymbol = "\\$";
        
        if (args.length != 4) {
            throw new JExpressionParserException("Summation expression arguments mismatched. You have to enter 4 arguments.");
        } else {
            BigInteger from, to;
            String variable, thefunction;
            from = new BigInteger(args[0]);
            to = new BigInteger(args[1]);
            if (from.compareTo(to) > 0) {
                throw new JExpressionParserException("Bounds of summation expression invalid: first bound must not be smaller than second bound!");
            }
            variable = args[2];
            thefunction = args[3];
            JMathExpList list = new JMathExpList();
            for (BigInteger i = from; i.compareTo(to) <= 0; i = i.add(BigInteger.ONE)) {
                list.add(parser.doDeepSolve(thefunction.replaceAll(varsymbol + variable + varsymbol, i + ""), 0));
            }
            return new JSum(list.getArray());
        }
    }

    @Override
    public List<String> getExpressionAliases() {
        return Arrays.asList(new String[] {"sigma", "summation"}); // hier lag der fail:  {"sigma, summation"}
    }
}
